package com.itdaan.portal.business.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.itdaan.portal.business.domain.Page;
import com.itdaan.portal.business.domain.Role;
import com.itdaan.portal.business.domain.User;
import com.itdaan.portal.business.domain.UserRole;
import com.itdaan.portal.business.mapper.UserMapper;
import com.itdaan.portal.business.mapper.UserRoleMapper;
import com.itdaan.portal.business.service.UserService;
import com.itdaan.portal.common.exception.ServiceException;
/**
 * @author www.itdaan.com
 */
@Service(value = "userService")
public class UserServiceImpl implements UserService{
	
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	
	public void insert(User user)  throws ServiceException{
		userMapper.insert(user);
	}
	
	public void insertWithDefaultRole(User user) throws ServiceException {
		userMapper.insert(user);
		// 新增加用户时同时赋给普通用户权限，可以发布文章
		// visitor账号创建后需要在后台去掉这个角色
		UserRole userRole = new UserRole();
		userRole.setUserId(user.getId());
		userRole.setRoleId(Role.ROLE_USER);
		userRoleMapper.insert(userRole);
	}

	/**
	 * 逻辑删除多个用户 。
	 * 
	 * @param ids 用逗号分隔的多个id字符串
	 */
	public void deleteByIds(String ids) throws ServiceException {
		for (String id : ids.split(",")) {
			User user = userMapper.getById(Integer.parseInt(id));
			user.setStatus(User.STATUS_DELETE);
			userMapper.update(user);
		}
	}
	
	public void update(User user) throws ServiceException {
		userMapper.update(user);
	}

	public User getById(int id) throws ServiceException {
		return userMapper.getById(id);
	}
	
	public User getByUserName(String username) throws ServiceException{
		return userMapper.getByUserName(username);
	}
	
	public User getByUidAndSource(String uid, int source) throws ServiceException {
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("uid", uid);
		params.put("source", source);
		return userMapper.getByUidAndSource(params);
	}
	
	public Page getByPage(Page page) throws ServiceException {
		List<Object> users = userMapper.getByPage(page);
		long count = userMapper.getCountByPage(page);
		page.setDatas(users);
		page.setCount(count);
		return page;
	}

	@Override
	public List<User> getNewestUsers(Map<String, Object> conditions)
			throws ServiceException {
		if(conditions == null){
			conditions = new HashMap<String,Object> ();
			conditions.put("start", 0);
			conditions.put("size", 50);
		}
		return userMapper.getNewestUsers(conditions);
	}
	
	
}
